<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElButton, ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElMessageBox, ElNotification } from 'element-plus';
import axios from 'axios';

const adminList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const profileDialogVisible = ref(false);
const adminForm = ref(null);
const profileForm = ref(null);
const searchQuery = ref('');

const token = localStorage.getItem('token');
const currentAccount = localStorage.getItem('account') || '';
const currentUsername = localStorage.getItem('username') || '';

const newAdmin = ref({
  account: '',
  username: '',
  password: ''
});

const updatedProfile = ref({
  newAccount: null,
  username: null,
  newPassword: null
});

const rules = ref({
  account: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入管理员用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
});

const profileRules = ref({
  newAccount: [
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
});

const pagedAdminList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  let filteredList = adminList.value;

  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase();
    filteredList = adminList.value.filter(admin =>
        admin.account.toLowerCase().includes(keyword) ||
        admin.username.toLowerCase().includes(keyword)
    );
  }

  return filteredList.slice(start, end);
});

const filteredTotal = computed(() => {
  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase();
    return adminList.value.filter(admin =>
        admin.account.toLowerCase().includes(keyword) ||
        admin.username.toLowerCase().includes(keyword)
    ).length;
  }
  return total.value;
});

const pageCount = computed(() => {
  return Math.ceil(filteredTotal.value / pageSize.value) || 1;
});

const axiosInstance = axios.create({
  baseURL: 'http://localhost:8080/api/admin',
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const fetchAdminList = async () => {
  loading.value = true;
  try {
    const response = await axiosInstance.get('/all');
    adminList.value = response.data.data || [];
    total.value = adminList.value.length;
  } catch (error) {
    console.error('Error fetching admin list:', error);
    ElMessage.error(`获取管理员列表失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

const submitForm = () => {
  adminForm.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await axiosInstance.post('/create-admin', newAdmin.value);
        if (response.data.success) {
          ElMessage.success('管理员创建成功');
          newAdmin.value = {
            account: '',
            username: '',
            password: ''
          };
          adminForm.value.resetFields();
          await fetchAdminList();
          dialogVisible.value = false;
        } else {
          ElMessage.error(`创建管理员失败: ${response.data.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('Error creating admin:', error);
        ElMessage.error(`创建管理员失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.warning('请检查表单输入');
      return false;
    }
  });
};

const handleAdminDeletion = () => {
  if (!token) {
    ElNotification({
      title: '操作失败',
      message: '无法找到有效的登录令牌。',
      type: 'error'
    })
    return
  }
  ElMessageBox.confirm(
      '您确定要删除当前管理员账户吗？此操作不可逆！所有相关数据将被永久删除。',
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        return axios.delete('http://localhost:8080/api/admin/me', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
      })
      .then(response => {
        ElNotification({
          title: '操作成功！即将跳转到登录页面...',
          message: response.data.message,
          type: 'success'
        })
        localStorage.clear();
        setTimeout(function () {
          window.location.href = '/login';
        }, 3000);
      })
      .catch(error => {
        let errorMessage = '删除管理员账户失败，请稍后重试。'
        if (error.response && error.response.data) {
          errorMessage = error.response.data.message || errorMessage
        }

        ElNotification({
          title: '操作失败',
          message: errorMessage,
          type: 'error'
        })
      })
}

const openDialog = () => {
  dialogVisible.value = true;
};

const openProfileDialog = () => {
  profileDialogVisible.value = true;
};

const handleSizeChange = (event) => {
  pageSize.value = parseInt(event.target.value);
  currentPage.value = 1;
};

const handleCurrentChange = () => {
  if (currentPage.value < 1) {
    currentPage.value = 1;
  } else if (currentPage.value > pageCount.value) {
    currentPage.value = pageCount.value;
  }
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < pageCount.value) {
    currentPage.value++;
  }
};

const goToPage = (page) => {
  currentPage.value = page;
};

const updateProfile = () => {
  profileForm.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await axiosInstance.put('/me/profile', updatedProfile.value);
        if (response.data.success) {
          ElMessage.success('个人信息更新成功');
          localStorage.setItem('username', response.data.data.username);
          localStorage.setItem('account', response.data.data.account);
          updatedProfile.value = {
            newAccount: null,
            username: null,
            newPassword: null
          };
          profileForm.value.resetFields();
          await fetchAdminList();
          profileDialogVisible.value = false;
        } else {
          ElMessage.error(`更新个人信息失败: ${response.data.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('Error updating profile:', error);
        ElMessage.error(`更新个人信息失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.warning('请检查表单输入');
      return false;
    }
  });
};

onMounted(() => {
  if (!token) {
    ElMessage.error('未找到认证令牌，请先登录');
    return;
  }
  fetchAdminList();
});
</script>

<template>
  <div class="admin-container">
    <div class="admin-header">
      <h1>管理员列表</h1>
    </div>

    <div class="admin-controls">
      <div class="search-container">
        <el-input
            v-model="searchQuery"
            placeholder="搜索账号或用户名"
            style="width: 300px;"
            clearable
        />
      </div>
      <div class="admin-form-container">
        <el-button type="primary" @click="openDialog">新增管理员</el-button>
        <el-button type="info" @click="openProfileDialog">修改个人信息</el-button>
        <el-button type="danger" @click="handleAdminDeletion" class="delete-btn">
          删除管理员账户
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <table class="custom-table">
        <thead>
        <tr>
          <th>ID</th>
          <th>账号</th>
          <th>用户名</th>
        </tr>
        </thead>
        <tbody>
        <tr
            v-for="admin in pagedAdminList"
            :key="admin.id"
            :class="{ 'highlighted': admin.account === currentAccount || admin.username === currentUsername }"
        >
          <td>{{ admin.id }}</td>
          <td>{{ admin.account }}</td>
          <td>{{ admin.username }}</td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-container">
      <div class="pagination">
        <div class="pagination-info">共 {{ filteredTotal }} 条</div>
        <div class="pagination-sizes">
          <span>每页显示:</span>
          <select v-model="pageSize" @change="handleSizeChange">
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
          </select>
        </div>
        <div class="pagination-buttons">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <span
              v-for="page in pageCount"
              :key="page"
              @click="goToPage(page)"
              :class="{ active: page === currentPage }"
          >
            {{ page }}
          </span>
          <button @click="nextPage" :disabled="currentPage === pageCount">下一页</button>
        </div>
        <div class="pagination-jumper">
          <input
              type="number"
              v-model.number="currentPage"
              @change="handleCurrentChange"
              :min="1"
              :max="pageCount"
          />
          <span>/ {{ pageCount }}</span>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="新增管理员" width="40%">
      <el-form ref="adminForm" :model="newAdmin" :rules="rules" label-width="120px">
        <el-form-item label="管理员账号" prop="account">
          <el-input v-model.trim="newAdmin.account" placeholder="输入新管理员账号"></el-input>
        </el-form-item>
        <el-form-item label="管理员用户名" prop="username">
          <el-input v-model.trim="newAdmin.username" placeholder="输入新管理员用户名"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input
              v-model.trim="newAdmin.password"
              type="password"
              placeholder="输入新管理员密码"
              show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">创建</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="profileDialogVisible" title="修改个人信息" width="40%">
      <el-form ref="profileForm" :model="updatedProfile" :rules="profileRules" label-width="120px">
        <el-form-item label="新的登录账号" prop="newAccount">
          <el-input v-model.trim="updatedProfile.newAccount" placeholder="输入新的登录账号"></el-input>
        </el-form-item>
        <el-form-item label="新的用户名" prop="username">
          <el-input v-model.trim="updatedProfile.username" placeholder="输入新的用户名"></el-input>
        </el-form-item>
        <el-form-item label="新的登录密码" prop="newPassword">
          <el-input
              v-model.trim="updatedProfile.newPassword"
              type="password"
              placeholder="输入新的登录密码"
              show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateProfile">更新</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.admin-header {
  text-align: center;
  margin-bottom: 20px;
}

.admin-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.admin-form-container {
  display: flex;
  gap: 10px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
}

.custom-table th, .custom-table td {
  border: 1px solid #ebeef5;
  padding: 12px 10px;
  text-align: left;
}

.custom-table th {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: bold;
}

.custom-table tr:nth-child(even) {
  background-color: #f9fafc;
}

.pagination-container {
  display: flex;
  justify-content: center;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 20px;
}

.pagination-info {
  margin-right: 10px;
}

.pagination-sizes select {
  padding: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.pagination-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-buttons button {
  padding: 6px 10px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-buttons button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-buttons span {
  display: inline-block;
  padding: 6px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-buttons span.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-jumper input {
  width: 50px;
  padding: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

.delete-btn {
  margin-left: 10px;
  width: 120px;
}

tr.highlighted {
  background-color: #e1f5fe !important;
  font-weight: bold;
}

tr.highlighted td {
  border-left: 4px solid #1890ff;
}
</style>